<?php
class CmsPhotoEditControl extends CmsBaseControl
{
    protected $photoId;
    protected $size;
    protected $model;
    protected $modelName = 'CmsPhoto';
    protected $jsClass = 'CmsPhotoEditControl';
    protected $jsFile = 'CmsPhotoEditControl';

    public function CmsPhotoEditControl($modelName = null)
    {
        parent::__construct();
        $this->photoId = RequestHandler::Get('photo_id');
        $this->modelName = $modelName ? $modelName : $this->modelName;
        $this->model = ModelBase::GetInstanceByName($this->modelName);
        $this->LoadSize();
    }

    protected function LoadSize()
    {
        $this->size = new Size(800, 460);
    }

    public function Render()
    {
        if (!$this->photoId) return $this->RenderStub();
        $photo = $this->model->FindById($this->photoId);
        if (!$photo) $photo = $this->model->GetEmptyRecord();
        $photo['url'] = Photo::GetInstance()->GetUrl($this->photoId, $this->size);
        $this->Replace($photo);
        $this->Replace('js', $this->GetJsScript());
        return parent::Render();
    }

    public function Save()
    {
        try
        {
            $item = RequestHandler::Get('photo');
            $item['id'] = $this->photoId;
            $this->model->Update($item);
            MessageBase::Confirm('Photo has been saved');
        }
        catch (Exception $ex)
        {
            MessageBase::Warning($ex->getMessage());
        }
        return $this->Render();
    }

    public function SetDefaultPhoto($photo_id)
    {
        $this->model->SetDefaultPhoto($photo_id);
        return $this->Render();
    }

    public function DeletePhoto($photo_id)
    {
        $this->model->Del($photo_id);
        return $this->Render();
    }
}
?>
